package com.b2c.repository;

import com.b2c.common.utils.DateUtil;
import com.b2c.entity.ShopRefundOrderEntity;
import com.b2c.entity.douyin.DouyinOrdersRefundEntity;
import com.b2c.entity.pdd.OrderPddItemEntity;
import com.b2c.entity.pdd.RefundPddEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.tao.TmallOrderRefundVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 描述：网店退货单service
 *
 * @author qlp
 * @date 2021-06-21 17:55
 */
@Repository
public class ShopRefundOrderRepository {
        @Autowired
        private JdbcTemplate jdbcTemplate;
        private static Logger log = LoggerFactory.getLogger(ShopRefundOrderRepository.class);

        @Transactional
        public List<ShopRefundOrderEntity> getShopRefundOrder(String num, Integer shopType) {
                if (StringUtils.isEmpty(num))
                        return null;

                List<ShopRefundOrderEntity> list = null;
                // 拼多多平台 先查pdd
                StringBuilder sb = new StringBuilder();
                sb.append("SELECT ");
                sb.append(
                                " pre.id as refundId,pre.order_sn,pre.tracking_number,pre.tracking_company,pre.shopId,sh.name as shopName");
                sb.append(
                                ",pre.sku_number,pre.quantity,sh.`type` as shopType,pre.`describe` as remark,sts.`name` as typeName ");
                sb.append(",pgs.spec as skuName,pre.goods_image,pre.goods_name");
                // sb.append(",egs.color_image as
                // goodsImage,concat(egs.color_value,egs.size_value) as
                // skuName,pre.goods_name");
                sb.append(",pre.after_sales_status,pre.after_sales_type,pre.created_time,pre.auditStatus,pre.auditTime");
                sb.append(" FROM dc_pdd_refund AS pre ");
                sb.append(" LEFT JOIN dc_shop AS sh on sh.id=pre.shopId ");
                sb.append(" LEFT JOIN dc_sys_third_setting AS sts on sts.id=sh.`type` ");
                sb.append(" LEFT JOIN dc_shop_goods_sku pgs on pgs.skuId=pre.skuId ");

                // sb.append(" LEFT JOIN erp_goods_spec AS egs on egs.specNumber=pre.sku_number
                // ");
                sb.append("   WHERE (pre.tracking_number=? or pre.order_sn =? or pre.id=? )");

                list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(ShopRefundOrderEntity.class), num,
                                num,
                                num);

                if (list == null || list.size() == 0) {
                        log.info("未查到pdd退货数据" + num + "，开始查询taobao退货数据....");
                        // 再查taobao
                        sb = new StringBuilder("SELECT ");
                        sb.append(
                                        " t.refund_id,t.tid as orderSn,t.logisticsCode as trackingNumber,t.logisticsCompany as trackingCompany");
                        sb.append(
                                        ",torder.shopId,sh.name as shopName,IFNULL(t.created,0) as createdTime, t.status as afterSalesStatus,sh.`type` as shopType,sts.`name` as typeName ");
                        sb.append(
                                        ",t.num as quantity,toi.goodsTitle as goodsName,toi.productImgUrl as goodsImage,toi.skuInfo as skuName,t.auditStatus,t.auditTime ");
                        sb.append(" FROM dc_tmall_order_refund t ");
                        sb.append(" LEFT JOIN dc_tmall_order torder on torder.id=t.tid ");
                        sb.append(" LEFT JOIN dc_tmall_order_items toi on toi.subItemId=t.oid ");
                        sb.append(" LEFT JOIN dc_shop AS sh on sh.id=torder.shopId ");
                        sb.append(" LEFT JOIN dc_sys_third_setting AS sts on sts.id=sh.`type` ");

                        sb.append(" WHERE t.logisticsCode=? OR t.refund_id=? OR t.tid=?");
                        // log.info(sb.toString());
                        list = jdbcTemplate.query(sb.toString(),
                                        new BeanPropertyRowMapper<>(ShopRefundOrderEntity.class), num, num,
                                        num);

                }

                if (list == null || list.size() == 0) {
                        // 再查抖店
                        log.info("未查到pdd、taobao退货数据" + num + "，开始查询douyin退货数据....");
                        sb = new StringBuilder("SELECT ");
                        sb.append(
                                        "refund.aftersale_id as refundId,IFNULL(UNIX_TIMESTAMP(refund.apply_time) /1000,0) AS createdTime,refund.order_id as orderSn");
                        sb.append(
                                        ",refund.product_pic as goodsImage,refund.product_name as goodsName,refund.spec_desc as skuName,refund.spec_code as skuNumber");
                        sb.append(
                                        ",refund.combo_num as quantity,refund.auditStatus,refund.auditTime,refund.logistics_company as trackingCompany,refund.logistics_code as trackingNumber,refund.remark");
                        sb.append(",refund.refund_status as afterSalesStatus,refund.aftersale_type as afterSalesType");
                        sb.append(",refund.shop_id,sh.name as shopName,sh.`type` as shopType,sts.`name` as typeName ");
                        sb.append(" FROM dc_douyin_orders_refund AS refund ");
                        sb.append(" LEFT JOIN dc_shop AS sh on sh.id=refund.shop_id ");
                        sb.append(" LEFT JOIN dc_sys_third_setting AS sts on sts.id=sh.`type` ");
                        sb.append(" WHERE refund.logistics_code=? OR refund.aftersale_id=? OR refund.order_id=?");
                        log.info(sb.toString());
                        list = jdbcTemplate.query(sb.toString(),
                                        new BeanPropertyRowMapper<>(ShopRefundOrderEntity.class), num, num,
                                        num);
                }

                return list;
        }

        @Transactional
        public ResultVo<Integer> refundReceiveConfirm(Long refundId, Integer shopType) {
                if (refundId == null || refundId <= 0 || shopType == null || shopType <= 0)
                        return new ResultVo<>(EnumResultVo.ParamsError, "参数错误，请检查产生refundId或shopType");

                if (shopType.intValue() == 5) {
                        // // 拼多多
                        // RefundPddEntity refund = jdbcTemplate.queryForObject("SELECT * from dc_pdd_refund where id=?",
                        //                 new BeanPropertyRowMapper<>(RefundPddEntity.class), refundId);

                        // jdbcTemplate.update(
                        //                 "UPDATE " + Tables.DcPddOrderRefund
                        //                                 + " SET auditStatus=2,sign=?,auditTime=? WHERE id=?",
                        //                 "确认签收" + DateUtil.getCurrentDateTime(), DateUtil.getCurrentDateTime(),
                        //                 refundId);

                        // // 2是已签收，下发到仓库系统
                        // String sql = "SELECT * FROM dc_pdd_orders_item oi LEFT JOIN dc_pdd_orders o on o.id=oi.order_id WHERE o.order_sn = ? ";
                        // var orderItem = jdbcTemplate.queryForObject(sql,
                        //                 new BeanPropertyRowMapper<>(OrderPddItemEntity.class),
                        //                 refund.getOrder_sn());
                        // Integer returnType = 1;
                        // if(refund.getAfter_sales_type().intValue() == 4){
                        //         returnType =2;//换货
                        // }else if(refund.getAfter_sales_type().intValue() == 9){
                        //         returnType =9;//拦截退货
                        // }
                        // String s = "INSERT INTO erp_order_send_return (orderSn,shopId,goodsId,goodsSpecId,goodsSpecNumber,logisticsCode,quantity,refundAmount,receiveTime,returnType,sourceNo) VALUE (?,?,?,?,?,?,?,?,?,?,?)";
                        // jdbcTemplate.update(s, refund.getOrder_sn(), refund.getShopId(),
                        //                 orderItem.getErpGoodsId(), orderItem.getErpGoodsSpecId(),
                        //                 orderItem.getGoodsSpecNum(),
                        //                 refund.getTracking_number(), refund.getQuantity(), refund.getRefund_amount(),
                        //                 DateUtil.getCurrentDateTime(),returnType,refund.getId());
                        return new ResultVo<>(EnumResultVo.SystemException,
                                        "未实现，refundId:" + refundId + ",shopType:" + shopType);

                } else if (shopType.intValue() == 6) {
                        // 抖音
                        DouyinOrdersRefundEntity refund = jdbcTemplate.queryForObject(
                                        "SELECT * from dc_douyin_orders_refund where aftersale_id=?",
                                        new BeanPropertyRowMapper<>(DouyinOrdersRefundEntity.class), refundId);

                        jdbcTemplate.update(
                                        "UPDATE dc_douyin_orders_refund SET refund_status=12,auditStatus=2,auditTime=?,remark=? WHERE aftersale_id=?",
                                        DateUtil.getCurrentDateTime(), "确认签收" + DateUtil.getCurrentDateTime(),
                                        refundId);
                        Integer returnType = 1;
                        if(refund.getAftersaleType().intValue() ==3){
                                //换货
                                returnType =2;
                        }
                        else if(refund.getAftersaleType().intValue() == 9){
                                returnType =9;//拦截退货
                        }
                        // 2是已签收，下发到仓库系统
                        String s = "INSERT INTO erp_order_send_return (orderSn,shopId,goodsId,goodsSpecId,goodsSpecNumber,logisticsCode,quantity,refundAmount,receiveTime,returnType,sourceNo) VALUE (?,?,?,?,?,?,?,?,?,?,?)";
                        jdbcTemplate.update(s, refund.getOrderId(), refund.getShopId(),
                                        refund.getErpGoodsId(), refund.getErpGoodsSpecId(), refund.getSpecCode(),
                                        refund.getLogisticsCode(), refund.getComboNum(), refund.getComboAmount(),
                                        DateUtil.getCurrentDateTime(),returnType,refund.getAftersaleId());

                }else if (shopType.intValue() == 4) {
                        // //淘宝
                        // TmallOrderRefundVo refundVo = jdbcTemplate.queryForObject("SELECT * FROM dc_tmall_order_refund WHERE refund_id=? ",new BeanPropertyRowMapper<>(TmallOrderRefundVo.class),refundId);

                        // if(refundVo.getErpGoodsId() ==null || refundVo.getErpGoodsId()<=0)
                        //     return new ResultVo<>(EnumResultVo.DataError,"数据错误，dc_tmall_order_refund中erpGoodsId值错误");
                        // if(refundVo.getErpGoodsSpecId() ==null || refundVo.getErpGoodsSpecId()<=0)
                        //     return new ResultVo<>(EnumResultVo.DataError,"数据错误，dc_tmall_order_refund中erpGoodsSpecId值错误");
                        // if(StringUtils.isEmpty(refundVo.getSpecNumber())) return new ResultVo<>(EnumResultVo.DataError,"数据错误，dc_tmall_order_refund中SpecNumber值错误");


                        // jdbcTemplate.update(
                        //                 "UPDATE dc_tmall_order_refund SET status=?,auditStatus=2,auditTime=?,receivedTime=?,remark=? WHERE refund_id=?",
                        //                 EnumDcTmallOrderReturnStatus.received.getIndex(),
                        //                 DateUtil.getCurrentDateTime(),
                        //                 DateUtil.getCurrentDateTime(),  "确认签收" + DateUtil.getCurrentDateTime(),
                        //                 refundId);
                        // Integer returnType = 1;
                        // if(refundVo.getAfterSalesType().intValue() ==3){
                        //         //换货
                        //         returnType =2;
                        // }
                        // // 2是已签收，下发到仓库系统
                        // String s = "INSERT INTO erp_order_send_return (orderSn,shopId,goodsId,goodsSpecId,goodsSpecNumber,logisticsCode,quantity,refundAmount,receiveTime,returnType,sourceNo) VALUE (?,?,?,?,?,?,?,?,?,?,?)";
                        // jdbcTemplate.update(s, refundVo.getTid(), refundVo.getShopId(),
                        //                 refundVo.getErpGoodsId(), refundVo.getErpGoodsSpecId(), refundVo.getSpecNumber(),
                        //                 refundVo.getLogisticsCode(), refundVo.getNum(), refundVo.getRefundFee(),
                        //                 DateUtil.getCurrentDateTime(),returnType,refundVo.getRefundId());


                        return new ResultVo<>(EnumResultVo.SystemException,
                                        "未实现，refundId:" + refundId + ",shopType:" + shopType);
                }       
                else {

                        return new ResultVo<>(EnumResultVo.SystemException,
                                        "未实现，refundId:" + refundId + ",shopType:" + shopType);
                }
                // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

                return new ResultVo<>(EnumResultVo.SUCCESS, "SUCCESS");
        }

        public ResultVo<Integer> signRefund(Long refundId, Integer shopType, Integer auditStatus, String remark) {
                if (refundId == null || refundId <= 0 || shopType == null || shopType <= 0)
                        return new ResultVo<>(EnumResultVo.ParamsError, "参数错误，请检查产生refundId或shopType");

                if (StringUtils.isEmpty(remark))
                        remark = "";

                if (shopType.intValue() == 5) {
                        RefundPddEntity refund = jdbcTemplate.queryForObject("SELECT * from dc_pdd_refund where id=?",
                                        new BeanPropertyRowMapper<>(RefundPddEntity.class), refundId);

                        if (StringUtils.hasText(refund.getDescribe()))
                                remark = refund.getDescribe() + remark;

                        jdbcTemplate.update("UPDATE " + Tables.DcPddOrderRefund
                                        + " SET auditStatus=?,sign=?,auditTime=?,`describe`=? WHERE id=?",
                                        auditStatus,
                                        "人工标记为[" + auditStatus + "]" + DateUtil.getCurrentDateTime(),
                                        DateUtil.getCurrentDateTime(),
                                        remark,
                                        refundId);
                } else if (shopType.intValue() == 6) {
                        // 抖音
                        DouyinOrdersRefundEntity refund = jdbcTemplate.queryForObject(
                                        "SELECT * from dc_douyin_orders_refund where aftersale_id=?",
                                        new BeanPropertyRowMapper<>(DouyinOrdersRefundEntity.class), refundId);
                        if (StringUtils.hasText(refund.getRemark()))
                                remark = refund.getRemark() + remark;
                        jdbcTemplate.update(
                                        "UPDATE dc_douyin_orders_refund SET auditStatus=?,auditTime=?,remark=? WHERE aftersale_id=?",
                                        auditStatus,
                                        DateUtil.getCurrentDateTime(), "人工标记为[" + auditStatus + "]" + DateUtil.getCurrentDateTime(),
                                        refundId);

                }else if(shopType.intValue() ==4){
                        String desc = jdbcTemplate.queryForObject("SELECT `remark` FROM dc_tmall_order_refund WHERE refund_id=?",String.class, refundId);
                        if(StringUtils.isEmpty(desc)) desc="";
                        if(StringUtils.isEmpty(remark)) remark="";
                        desc = desc + remark;
                        desc += "人工标记为[" + auditStatus + "]" + DateUtil.getCurrentDateTime();
                
                        jdbcTemplate.update("UPDATE dc_tmall_order_refund SET auditStatus=?,auditTime=?,`remark`= ? WHERE refund_id=?",
                        auditStatus,
                        DateUtil.getCurrentDateTime(),desc,
                        refundId);
                }
                 else {

                        return new ResultVo<>(EnumResultVo.SystemException,
                                        "未实现，refundId:" + refundId + ",shopType:" + shopType);
                }
                return new ResultVo<>(EnumResultVo.SUCCESS, "SUCCESS");
        }

        public ResultVo<Integer> signRemark(Long refundId, Integer shopType, String remark) {
                if (refundId == null || refundId <= 0 || shopType == null || shopType <= 0)
                        return new ResultVo<>(EnumResultVo.ParamsError, "参数错误，请检查产生refundId或shopType");

                if (StringUtils.isEmpty(remark)) return new ResultVo<>(EnumResultVo.ParamsError, "参数错误，remark不能为空");
                if (shopType.intValue() == 5) {
                        jdbcTemplate.update("update dc_pdd_refund set `describe`=?,auditTime=? where id=?",remark,DateUtil.getCurrentDateTime(),refundId);
                } else if (shopType.intValue() == 6) {
                        jdbcTemplate.update("update dc_douyin_orders_refund set `remark`=?,auditTime=? where aftersale_id=?",remark,DateUtil.getCurrentDateTime(),refundId);
                }
                else {

                        return new ResultVo<>(EnumResultVo.SystemException,
                                        "未实现，refundId:" + refundId + ",shopType:" + shopType);
                }
                return new ResultVo<>(EnumResultVo.SUCCESS, "SUCCESS");
            }

        
}
